const baseUrl = 'http://openpay.duolaibei.com';
const httpRequest = (opts, data) => {
	let httpDefaultOpts = {
		url: baseUrl + opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			'X-Requested-With': 'XMLHttpRequest',
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				resolve(res[1])
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};
//原生地址请求
const h5Request = (opts, data) => {
	let httpDefaultOpts = {
		url: opts.url,
		data: data,
		method: opts.method,
		header: opts.method == 'get' ? {
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		} : {
			'X-Requested-With': 'XMLHttpRequest',
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		},
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				resolve(res[1])
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};

//带Token请求
const httpTokenRequest = ({
	url,
	method,
	data,
	needToken = true
}) => {
	var token = "";
	if (needToken) {
		uni.getStorage({
			key: 'token',
			success: function(ress) {
				token = ress.data
			},
			fail: (err) => {
				uni.reLaunch({
					url: '/pages/login/login'
				})
			}
		});
	}
	let getToken = {
			"Accept": "application/json",
			"Content-Type": "application/json; charset=UTF-8"
		},
		postToken = {
			'Token': token,
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		};
	if (!needToken) {
		postToken = {
			'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
		}
	}
	//此token是登录成功后后台返回保存在storage中的
	let httpDefaultOpts = {
		url: baseUrl + url,
		data: data,
		method: method,
		header: method == 'get' ? getToken : postToken,
		dataType: 'json',
	}
	let promise = new Promise(function(resolve, reject) {
		uni.request(httpDefaultOpts).then(
			(res) => {
				let r=res[1];
				if(r.data.code===1001||r.data.code===1002||r.data.code===1003){
					uni.showToast({
						title:r.data.msg,
						icon:'none',
						duration:2000
					});
					uni.reLaunch({
						url: '/pages/login/login'
					})
				}else{
					resolve(res[1])
				}
				
			}
		).catch(
			(response) => {
				reject(response)
			}
		)
	})
	return promise
};

export default {
	baseUrl,
	httpRequest,
	httpTokenRequest,
	h5Request
}
